const { layer, form } = layui;


let addOpen;

let editOpen;
$(function () {
    reqArticles();

    // 添加类别的按钮事件
    $('#btnAddCate').click(() => {
        addOpen = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '添加文章分类',
            content: $('#dialog-add').html(),
        })
    });

    addArticle();


    // 编辑按钮绑定事件
    $('tbody').on('click', '.btn-edit', async function () {
        const id = $(this).attr('data-id');
        await renderEditForm(id);
        editOpen = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '编辑文章分类',
            content: $('#dialog-edit').html(),
        })
    });

    // 触发修改按钮事件
    $('.submitEdit').click(() => {
        form.on('submit(editForm)', function (value) {
            console.log(value);
            return false;
        })
    });

    // 删除按钮事件
    $('tbody').on('click', '.btn-delete', function () {
        const id = $(this).attr('data-id');
        layer.alert('确认删除吗？', { icon: 3, title: '提示' }, (index) => {
            $.get(`/my/article/deletecate/${id}`, result => {
                const { status } = result;
                if (status === 0) {
                    layer.msg('删除成功');
                    reqArticles();
                } else {
                    layer.msg('删除失败');
                }
            })
            layer.close(index);
        })
    })
})

// 获取文章分类的数据
function reqArticles() {
    $.get('/my/article/cates', result => {
        $('tbody').html(template('tpl-table', result));
    })
}

// 添加文章分类
function addArticle() {
    form.on('submit(formDemo)', value => {
        $.post('/my/article/addcates', value.field, result => {
            const { status } = result;
            if (status === 0) {
                layer.msg('添加分类成功');
                reqArticles();
                form.render(null, 'form-add');
                layer.close(addOpen);
            } else {
                layer.msg('添加分类失败');
            }
        })
        return false;
    })
}

// 渲染编辑表单
function renderEditForm(id) {
    $.get(`/my/article/cates/${id}`, result => {
        const { data } = result;
        form.val('form-edit', data);
    })
}